<template>
    <div class="order">
        <div class="order-header">
            <el-button v-for="(button, index) in buttons" :key="index" :class="{ 'active': selectedButton === index }"
                @click="selectButton(index)">
                {{ button }}
            </el-button>
        </div>

        <!-- <button @click="sendMessage">发送消息</button> -->

        <div class="order-content">
            <div class="order-content-header">
                <el-text class="order-content-header-number">订单号：</el-text>
                <el-input v-model="form.number" style="width: 160px" placeholder="请输入订单号" clearable />

                <el-text class="order-content-header-userPhone">手机号：</el-text>
                <el-input v-model="form.userPhone" style="width: 160px" placeholder="请输入手机号" clearable />

                <el-text class="order-content-header-orderTime">下单时间：</el-text>
                <el-date-picker style="width: 200px" v-model="date" type="daterange" start-placeholder="开始日期"
                    end-placeholder="结束日期" format="YYYY-MM-DD " date-format="YYYY/MM/DD " @change="handleDateChange" />

                <el-button type="warning" round @click="handleSearch">查询</el-button>
            </div>
            <div class="order-content-body">
                <el-table :data="tableData" stripe height="450" style="width: 100%">
                    <el-table-column prop="number" label="订单号">
                    </el-table-column>
                    <el-table-column prop="status" label="订单状态">
                        <template v-slot="scope">
                            {{
                                scope.row.status === 1 ? '待付款' :
                                    scope.row.status === 2 ? '已接单' :
                                        scope.row.status === 3 ? '已完成' :
                                            scope.row.status === 4 ? '已取消' :
                                                scope.row.status === 5 ? '已退款' :
                                                    '未知状态'
                            }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="userName" label="用户名">
                    </el-table-column>
                    <el-table-column prop="userPhone" label="手机号">
                    </el-table-column>
                    <el-table-column prop="orderTime" label="下单时间">
                    </el-table-column>
                    <el-table-column prop="amount" label="实收金额">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button link type="primary" v-if="scope.row.status === 2" style="color: red;"
                                @click="handleCancel(scope.row)">取消</el-button>
                            <el-button link type="primary" @click="handleSee(scope.row)">查看</el-button>

                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="pageList" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="form.page" :page-sizes="[10, 20, 30, 40, 50]" :page-size="form.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="form.total">
                </el-pagination>
            </div>
            <el-dialog v-model="centerDialogVisibleCancel" title="取消订单原因(退款)" width="500" align-center>
                <div class="dialog-body">
                    <div class="dialog-body-cancelReason">
                        <el-text>取消原因：</el-text>
                        <el-select v-model="cancelReason" placeholder="请选择取消原因">
                            <el-option label="订单异常" value="订单异常" />
                            <el-option label="自定义原因" value="自定义原因" />
                        </el-select>
                    </div>
                    <div class="dialog-body-cancelReason-ziDingYi" v-if="cancelReason === '自定义原因'">
                        <el-text>原因：</el-text>
                        <el-input v-model="customReason" style="width: 330px" placeholder="请输入自定义原因(最多30字)"
                            type="textarea" />
                    </div>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="handleCancelOrder">取消</el-button>
                        <el-button type="primary" @click="handleConfirmOrder">
                            确认
                        </el-button>
                    </div>
                </template>
            </el-dialog>

            <el-dialog v-model="centerDialogVisibleConfirm" width="800" align-center>

                <el-descriptions title="详情信息列表" :column="3" border>
                    <el-descriptions-item label="下单名称" label-align="right" align="center" label-class-name="my-label"
                        class-name="my-content" width="80px">
                        {{ ViewConfirmedData.userName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="电话号码" align="center" width="100px">
                        {{ ViewConfirmedData.userPhone }}
                    </el-descriptions-item>
                    <el-descriptions-item label="结账时间" align="center" width="120px">
                        {{ ViewConfirmedData.checkoutTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="预约医护" label-align="right" align="center">
                        <el-tag size="small">
                            {{ ViewConfirmedData.staffName }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单号码" align="center">
                        {{ ViewConfirmedData.number }}
                    </el-descriptions-item>
                    <el-descriptions-item label="订单状态" align="center">
                        {{
                            ViewConfirmedData.status === 1 ? '已接单' :
                                ViewConfirmedData.status === 2 ? '已接单' :
                                    ViewConfirmedData.status === 3 ? '已完成' :
                                        ViewConfirmedData.status === 4 ? '已取消' :
                                            ViewConfirmedData.status === 5 ? '已退款' :
                                                '未知状态'
                        }}
                    </el-descriptions-item>
                </el-descriptions>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="warning" v-if="ViewConfirmedData.status === 2"
                            @click="CallNumber">叫号</el-button>
                        <el-button type="success" v-if="ViewConfirmedData.status === 2" @click="handleFinishOrder">
                            完成订单
                        </el-button>
                        <el-button type="info" @click="viewCancelView">取消查看</el-button>
                    </div>
                </template>

                <el-dialog v-model="viewCallNumbers" width="500" title="叫号" append-to-body>

                    <div class="dialog-body">
                        <div class="dialog-body-cancelReason">
                            <el-text>叫号原因：</el-text>
                            <el-select v-model="callNumber.callNumberCancelReason" placeholder="请选择叫号原因"
                                style="width: 300px">
                                <el-option label="请前往就诊" value="请前往就诊" />
                                <el-option label="自定义原因" value="自定义原因" />
                            </el-select>
                        </div>
                        <div style="display: flex; margin-top: 10px;"
                            v-if="callNumber.callNumberCancelReason === '自定义原因'">
                            <el-text>原因：</el-text>
                            <el-input style="width: 330px" v-model="callNumber.callNumberCustomReason"
                                placeholder="请输入自定义原因" type="textarea" />
                        </div>
                    </div>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="callCancellation">取消</el-button>
                            <el-button type="primary" @click="CallConfirmation">
                                确认
                            </el-button>
                        </div>
                    </template>
                </el-dialog>

            </el-dialog>
            <el-dialog v-model="confirmFinishVisible" title="确认完成订单" width="400px" center>
                <span>
                    您确定要完成此订单吗？
                </span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="cancelFinishOrder">取消</el-button>
                        <el-button type="primary" @click="confirmFinishOrder">确认</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { useWebSocketStore } from '@/stores/websocket';
import { getOrders, rejectionOrder, confirmOrder } from "@/api/orders"
import { ref, onMounted } from 'vue';
const { websocket } = useWebSocketStore();



// 这个表单负责存储搜索条件和分页信息
const form = ref({
    status: null, // 状态
    number: '', // 订单号
    userPhone: '', // 手机号
    orderStartTime: '', // 下单开始时间
    orderEndTime: '', // 下单结束时间
    page: 1, // 当前页
    pageSize: 10, // 每页显示条数
    total: 0 // 总条数
});
// 表格数据
const tableData = ref([]);
const date = ref('')
const cancelReason = ref('');
const customReason = ref('');
const centerDialogVisibleCancel = ref(false);
const centerDialogVisibleConfirm = ref(false);
const viewCallNumbers = ref(false);
const dataRejection = ref({
    orderId: '',
});
const selectedButton = ref(0); // 默认选中第一个按钮
const buttons = ['全部', '已接单', '已完成', '已取消', '已退款'];
const ViewConfirmedData = ref({}); // 存储查看订单详情的数据
// 添加一个用于控制确认对话框显示状态的变量
const confirmFinishVisible = ref(false);

const callNumber = ref({
    callNumberCancelReason: '', // 叫号原因
    callNumberCustomReason: '', // 自定义叫号原因
})

// 完成订单
const handleFinishOrder = () => {
    console.log('请求完成订单:', ViewConfirmedData.value);
    confirmFinishVisible.value = true; // 显示确认对话框
};

// 确认完成订单
const confirmFinishOrder = () => {
    console.log('完成订单:', ViewConfirmedData.value);
    confirmOrder(ViewConfirmedData.value.id).then(res => {
        console.log('完成订单结果:', res);
        ElMessage.success('完成订单成功');
        handleSearch();
        centerDialogVisibleConfirm.value = false;
    }).catch(err => {
        console.log('完成订单失败:', err);
        ElMessage.error('完成订单失败');
    });
    confirmFinishVisible.value = false; // 关闭确认对话框
};

// 取消完成订单
const cancelFinishOrder = () => {
    confirmFinishVisible.value = false; // 关闭确认对话框
};

function sendMessage() {
    const message = {
        userId: `${ViewConfirmedData.value.userId}`,
        content: callNumber.value.callNumberCancelReason === '自定义原因' ?
            callNumber.value.callNumberCustomReason : callNumber.value.callNumberCancelReason
    };

    if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
        websocket.value.send(JSON.stringify(message)); // 发送JSON格式的消息
    } else {
        console.error('WebSocket is not connected.');
    }
}

// 确认叫号
const CallConfirmation = () => {
    // 发送消息
    sendMessage();
    ElNotification({
        title: '叫号成功',
        type: 'success',
    })
    callCancellation()

};

// 取消叫号
const callCancellation = () => {
    // console.log('取消叫号');
    callNumber.value.callNumberCancelReason = '';
    callNumber.value.callNumberCustomReason = '';
    viewCallNumbers.value = false;
};

const handleSee = (row) => {
    console.log('查看订单:', row);
    // 存储查看订单详情的数据
    ViewConfirmedData.value = row;
    centerDialogVisibleConfirm.value = true;
};

const CallNumber = () => {
    viewCallNumbers.value = true;
}

// 拒单订单
const handleCancel = (row) => {
    console.log('取消订单:', row);
    centerDialogVisibleCancel.value = true;
    // 定义要传递的数据
    dataRejection.value.orderId = row.id;

};

// 查看取消查看
const viewCancelView = () => {
    centerDialogVisibleConfirm.value = false;
};


const handleCancelOrder = () => {
    cancelReason.value = '';
    customReason.value = '';
    centerDialogVisibleCancel.value = false;
};
const handleConfirmOrder = () => {
    console.log('确认取消订单:', cancelReason.value, customReason.value);
    const data = {
        id: dataRejection.value.orderId,
        rejectionReason: cancelReason.value === '自定义原因' ? customReason.value : cancelReason.value
    };
    // 调用取消订单接口，并传递数据
    rejectionOrder(data).then(res => {
        console.log('拒单订单结果:', res);
        ElMessage.success('拒单订单成功');
        // 刷新订单列表
        handleSearch();
        handleCancelOrder();
    }).catch(err => {
        console.log('取消订单失败:', err);
        ElMessage.error('取消订单失败');
    });
};

const selectButton = (index) => {
    selectedButton.value = index;
    console.log('选中按钮:', selectedButton);
    switch (index) {
        case 0:
            form.value.status = null; // 全部时不发送参数
            handleSearch() // 重新查询
            break;
        case 1:
            form.value.status = 2; // 已接单
            handleSearch() // 重新查询
            break;
        case 2:
            form.value.status = 3; // 已完成
            handleSearch() // 重新查询
            break;
        case 3:
            form.value.status = 4; // 已取消
            handleSearch() // 重新查询

            break;
        case 4:
            form.value.status = 5; // 已退款
            handleSearch() // 重新查询
            break;
    }
    console.log('选中状态:', form.value.status);
};

// 处理分页逻辑
const handleSizeChange = (newSize) => {
    form.value.pageSize = newSize
    form.value.pageSize = newSize
    handleSearch()
}

// 处理当前页逻辑
const handleCurrentChange = (newPage) => {
    form.value.page = newPage
    form.value.page = newPage
    handleSearch()
}

const handleDateChange = (value) => {
    // 检查 value 是否有效
    if (!value || value.length < 2) {
        console.log('日期选择已清除');
        return; // 如果没有选择有效的日期，直接返回
    }
    console.log('选择的日期范围:', value);
    // 这里假设 `value` 是一个数组，包含选择的开始日期和结束日期
    const startDate = value[0];
    const endDate = value[1];
    // 输出格式化后的日期
    console.log('选择的开始日期:', formatDate(startDate, true)); // 传递 true 表示包含时间
    console.log('选择的结束日期:', formatDate(endDate, true)); // 传递 true 表示包含时间
    // 将日期赋值到表单
    form.value.orderStartTime = formatDate(startDate, true);
    form.value.orderEndTime = formatDate(endDate, true);
};

// 处理搜索条件
const handleSearch = () => {
    // 重新查询
    getOrders(form.value).then(res => {
        // console.log('订单列表:', res);
        tableData.value = res.data.records
        form.value.total = res.data.total;
    }).catch(err => {
        // console.log('订单列表查询失败:', err);
        ElMessage.error('订单列表查询失败');
    });
};

// 页面加载完成后，自动查询一次订单列表
onMounted(() => {
    // 订单条件分页查询
    getOrders(form.value).then(res => {
        // console.log('订单列表:', res);
        tableData.value = res.data.records
        form.value.total = res.data.total;
    }).catch(err => {
        // console.log('订单列表查询失败:', err);
        ElMessage.error('订单列表查询失败');
    });

})

// 格式化日期为 YYYY-MM-DD'T'HH:mm:ss
const formatDate = (date, includeTime = false) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(d.getDate()).padStart(2, '0');

    if (includeTime) {
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`; // 添加'T'字符
    } else {
        return `${year}-${month}-${day}`; // 只返回日期
    }
};


</script>

<style lang="scss">
.order {
    .order-header {
        .el-button {
            // 清除默认按钮样式
            border: none;
            margin: 1px;
            width: 80px;
            height: 40px;
            border: 1px solid #ccc;

            &.active {
                background-color: #D8E699; // 选中按钮的背景色
                color: #000; // 选中按钮的文字颜色
            }

            
        }
    }

    .order-content {
        margin-top: 15px;
        padding: 10px;
        background-color: #fff;

        .order-content-header {
            .order-content-header-number {
                margin-right: 10px;
            }

            .order-content-header-userPhone {
                margin: 0 10px;
            }

            .order-content-header-orderTime {
                margin: 0 10px;
            }

            .el-button {
                margin-left: 30px;
                color: #fff;
                background-color: #000;

            }
        }

        .order-content-body {
            .el-table {
                margin-top: 10px;

                // width: 100%;
                // height: 100%;
            }

            .pageList {
                margin-top: 20px;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        }

        .dialog-body {
            .dialog-body-cancelReason {
                display: flex;
                margin-bottom: 10px;

                .el-select {
                    width: 300px;
                }
            }

            .dialog-body-cancelReason-ziDingYi {
                display: flex;
                margin-bottom: 10px;

            }


        }
    }
}
</style>
